import React, { useState, useEffect, useCallback,useRef } from 'react';
import type { FormInstance } from 'antd';
import type { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import { Modal, message, Select, Button } from 'antd';
import { FilterOutlined, PlusOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { useActivate } from 'react-activation';
import {
  getTreeData,
  getSubsystem,
  modifyStatus,
  authorization_check,
  deleteByIds
} from '@/services/sysSetting';
import { getStatusMap } from '@/services/common';
const UserManage: React.FC = (props:any) => {
  let { location:{state} } = props;
  const ref = useRef<FormInstance>();
  
  const [sysResourceType, setSysResourceType] = useState([]); // 资源状态
  const [sysCommonStatus, setSysCommonStatus] = useState([]); // 资源类型
  const [subsystem, setSubsystem] = useState([]); // 子类型列表
  const [changeSubsystemCode, setChangeSubsystemCode] = useState(''); // 子类型选中项key
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); // 勾选的数据id集合

  useEffect(() => {
    // 获取查询条件中资源类型（sys_resource_type）和资源状态（sys_common_status）的下拉列表的数据
    getInitData(getStatusMap,'sys_resource_type',setSysResourceType);
    getInitData(getStatusMap,'sys_common_status',setSysCommonStatus);
    // 获取子系统下拉数据
    getInitData(getSubsystem,{},setSubsystem);
  }, []);
 
   // 页面缓存之后，再次打开更新接口数据
  useActivate(() => {
    if (state === 'callback') {
      reloadTableFun();
    };
  })

  // 获取所有的初始参数  
  const getInitData = (interfaceName:any,params:any,setFun:any) => {
    interfaceName(params).then((res:any) => {
      if (res?.code === 200) {
        if (typeof params === 'object') {
          let resData = res.data || [];
          for (let item of resData) {
            item.label = item.name;
            item.key = item.subsystemCode;
          }
          setFun(resData);
          // 设置默认的子系统，数据集的第一条
          setChangeSubsystemCode(resData[0].key);
        }else{
          setFun(res.data);
        }
      }
    });
  };
  const startStopTips = (tips:string) =>{
    if (selectedRowKeys.length === 0) {
      return message.info('请选择操作项');
    };
    startStopDelete(tips);
  }
  // 启用/停用/删除
  const startStopDelete = (tips:string,idList:Array<string | number> = selectedRowKeys) => {
    authorization_check({resourceIdList:idList}).then(res=>{
      if (res.code === 200) {
        Modal.confirm({
          title: `${tips}的提示信息`,
          content: tips === '删除' ? 
          (res.data ? '当前菜单存在已使用客户，您需要取消客户配置才可删除' : '确认删除吗？') :
          (res.data ? `当前菜单存在已使用客户，您确定${tips}吗？` : `您确定${tips}吗？`),
          onOk:()=>{
            let interfaceName:any = '';
            let params:any = {};
            if(tips === '删除'){
              interfaceName = deleteByIds;
              params = {idList};
            }else{
              interfaceName = modifyStatus;
              params = {idList,status:tips === '启用' ? '1' : '0'};
            };
            interfaceName(params).then((res:any)=>{
              if (res.code === 200) {
                reloadTableFun();
                message.success('操作成功');
              }else{
                message.error(res.message);
              }
            });
          },
          onCancel:()=>{},
        });
      }else{
        message.warn(res.message);
      }
    })
  };
  // 重查表格数据
  const reloadTableFun = () =>{
    ref?.current?.submit();
    setSelectedRowKeys([]);
  }; 
  // 详情/编辑/新增 跳转逻辑
  const toMeunOperation = (jumpType:string, Id:string = '') => {
    history.push({
      pathname: '/features/sysSetting/menuOperation',
      state:{
        changeSubsystemCode,
        jumpType,
        Id
      }
    })
  }
  const TableCustomDeploy = {
    componentName: 'customTable',
  };
  const requestHandle = async (params: any) => {
    let res = getTreeData(params)
    return Promise.resolve(res);
  };

  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    // 表格的columns
    const columns: ProColumns[] = [
      {
        title: '资源名称',
        dataIndex: 'name',
        width:200,
        valueType: 'text',
        order: 1,
      },
      {
        title: (_, type) => (type === 'table' ? '类型' : '资源类型'),
        dataIndex: 'type',
        width:100,
        valueType: 'text',
        order: 3,
        valueEnum: {
          1: { text: '子系统', },
          2: { text: '菜单', },
          3: { text: '操作', },
        },
        renderFormItem: (_, { ...rest }) => {
          return (
            <Select
            showSearch
            placeholder='请选择资源类型'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            allowClear
            notFoundContent={null}
            {...rest}
            // onChange={(val)=>{
            //   (rest as any).onChange(val);
            // }}
          >
            {sysResourceType&&sysResourceType.map((item:any)=>{
              return <Select.Option key={item.id} value={item.dictValue}>{item.dictLabel}</Select.Option>
            })}
          </Select>
          );
        },
      },
      {
        title: (_, type) => (type === 'table' ? '状态' : '资源状态' ),
        dataIndex: 'status',
        width:80,
        order: 2,
        valueEnum: {
          0: { text: '停用', status: 'Error' },
          1: { text: '启用', status: 'Success' },
        },
        renderFormItem: (_, { ...rest }) => {
          return (
            <Select
            showSearch
            placeholder='请选择资源类型'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            allowClear
            notFoundContent={null}
            {...rest}
            // onChange={(val)=>{
            //   (rest as any).onChange(val);
            // }}
          >
            {sysCommonStatus&&sysCommonStatus.map((item:any)=>{
              return <Select.Option key={item.id} value={item.dictValue}>{item.dictLabel}</Select.Option>
            })}
          </Select>
          );
        },
      },
      {
        title: '访问地址',
        dataIndex: 'routeUrl',
        width:180,
        ellipsis:true,
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: 'ICON',
        dataIndex: 'icon',
        width:120,
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '权限标识',
        dataIndex: 'apiUrls',
        valueType: 'text',
        ellipsis:true,
        width:180,
        hideInSearch: true,
      },
      {
        title: '资源排序',
        dataIndex: 'sortOrder',
        width:80,
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '资源权重',
        dataIndex: 'weightLevel',
        width:80,
        valueType: 'text',
        hideInSearch: true,
        valueEnum: {
          '-1': { text: 'system', },
          '1': { text: 'admin', },
          '2': { text: '其他', },
        },
      },
      {
        title: '操作',
        width:300,
        fixed:"right",
        valueType: 'option',
        render: (text, record, _, action) => [
          <Button size="small" type="text" onClick={()=>toMeunOperation('details',record.id)}>详情</Button>,
          <Button size="small" type="text" onClick={()=>toMeunOperation('edit',record.id)}>编辑</Button>,
          (record.status == 1 ? <Button size="small" type="link" danger onClick={()=>startStopDelete('停用',[record.id])}>停用</Button> :
           <Button size="small" type="link" onClick={()=>startStopDelete('启用',[record.id])}>启用</Button>),
          (record.type != 3 ? <Button size="small" type="link" onClick={()=>toMeunOperation('add',record.id)}>新增</Button> :
           <p style={{width:"44px"}}></p>),
          <Button size="small" type="link" danger onClick={()=>{startStopDelete('删除',[record.id])}}>删除</Button>,
        ]
      },
      {
        title: '终端类型',
        dataIndex: 'clientType',
        valueType: 'text',
        hideInTable:true,
        order: 4,
        valueEnum: {
          1: { text: 'H5', },
          2: { text: 'PC', },
          3: { text: 'PAD', },
        },
      },
    ];
    const rowSelection = {
      onChange: (rowKeys: React.Key[], selectedRows: any[]) => {
        setSelectedRowKeys(rowKeys);
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    return {
      columns,
      manualRequest:true, //手动触发第一次请求。防止第一次自动的请求没有带上subsystemCode参数
      request: async (params = {}, sort, filter) => {
        return requestHandle(params);
      },
      // 添加额外的请求参数
      params:{
        subsystemCode: changeSubsystemCode
      },
			scroll:{ x: 1000 },
      formRef:ref,
      rowSelection: {
        type: 'checkbox',
        ...rowSelection,
        selectedRowKeys,
        checkStrictly:false
      },
      pagination: {
        pageSize: 10,
      },
      // expandable:{
      //   expandRowByClick:true
      // },
      toolbar:{
        menu: {
          type: 'dropdown',
          items: subsystem,
          activeKey:changeSubsystemCode, // 默认选中
          onChange: (activeKey) => {
            setChangeSubsystemCode(activeKey as string);
          },
        },
      },
      rowKey: 'id',
      toolBarRender: () => [
        <Button icon={<PlusOutlined />} onClick={()=>toMeunOperation('addSystem')}>新增</Button>,
        <Button onClick={()=>startStopTips('停用')}>停用</Button>,
        <Button onClick={()=>startStopTips('启用')}>启用</Button>,
      ],
    };
  };
  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };
  return (
    <div>
      <ProTable {...jsonOption}></ProTable>
    </div>
  );
};

export default UserManage;
